package com.eroad.offer.sina;

import java.util.HashMap;

import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;

import com.sky.widget.SHDialog;
import com.sky.widget.SHToast;
import com.sky.zzh.util.ConfigDefinition;

/**
 * 新浪登录
 * 
 * @author 陈彬
 * 
 */
@SuppressLint("SimpleDateFormat")
public class SinaLogin {

	private Context context;
	
	private static final int MSG_AUTH_CANCEL = 2;
	private static final int MSG_AUTH_ERROR= 3;
	private static final int MSG_AUTH_COMPLETE = 4;
	private Handler handler = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch(msg.what) {
			case MSG_AUTH_CANCEL: {
				//取消授权
				SHToast.showToast(context, "取消授权");
			} break;
			case MSG_AUTH_ERROR: {
				//授权失败
				SHToast.showToast(context, "授权失败");
			} break;
			case MSG_AUTH_COMPLETE: {
				SHToast.showToast(context, "授权成功");
				new OtherLogin(loginInfo, context).login();
			} break;
		}
		}
		
	};

	private LoginInfo loginInfo;

	public SinaLogin(Context c, boolean share) {
		this.context = c;

		loginInfo = new LoginInfo();

	}

	public void sinaLogin() {
		Platform plat_sina = ShareSDK.getPlatform(context, SinaWeibo.NAME);
		plat_sina.setPlatformActionListener(new PlatformActionListener() {

			@Override
			public void onError(Platform arg0, int action, Throwable t) {
				// TODO Auto-generated method stub
				if (action == Platform.ACTION_USER_INFOR) {
					handler.sendEmptyMessage(MSG_AUTH_ERROR);
				}
				t.printStackTrace();
			}

			@Override
			public void onComplete(Platform plat, int action, HashMap<String, Object> map) {
				// TODO Auto-generated method stub
				PlatformDb db = plat.getDb();
				loginInfo.setOpenid(db.getUserId());
				loginInfo.setToken(db.getToken());
				loginInfo.setType("sina.com");
				loginInfo.setNickname(db.getUserName());
				loginInfo.setUserphoto(db.getUserIcon());
				if (action == Platform.ACTION_USER_INFOR) {
					Message msg = new Message();
					msg.what = MSG_AUTH_COMPLETE;
					handler.sendMessage(msg);
				}
			}

			@Override
			public void onCancel(Platform arg0, int action) {
				// TODO Auto-generated method stub
				if (action == Platform.ACTION_USER_INFOR) {
					handler.sendEmptyMessage(MSG_AUTH_CANCEL);
				}
			}
		});
		// 关闭SSO授权
		plat_sina.SSOSetting(true);
		plat_sina.showUser(null);
	}

}
